<?php
/**
 *Notes: 首页按钮助手
 *Author:lichunyong
 *DateTime:2022/06/13 10:35
 */

namespace Xtsb\Cims\Btn;

use think\facade\Db;
use think\Paginator;

class BtnHelper
{
  static $btnList;

  /**自定义右边按钮
   * @param          $item
   * @param string[] $list （修改，删除，回测，详情）
   * @param string 如果需要打印，需要传入所处的动态路由的文件夹， 例如： Epc\Storage\Goods等
   * @param boolean $isAudit 是否是审批数据，
   *                            true：如果是审批数据，需要根据： 创建人/当前处理人/状态/步骤来判断是否显示删除、编辑等按钮,
   *                            false；其他不涉及审批页面的，不包含status\step_id的，请传false
   * @param array $pageParam 需要传递的其他btn参数
   *                            [
   *                            'edit_btn_param'=>['save'=>false,'submit'=>false],  //编辑页面， 需要隐藏保存/提交按钮
   *                            'delete_tip'=>'', //删除按钮，需要展示的提示信息
   *                            ]
   * @param boolean $forceDelete 是否是有强制删除权限，
   *                            true：有,
   *                            false；无,
   * @return array 按钮数据
   */
  static function rightBasicBtn($item, $list = ['edit', 'delete', 'recall', 'read'], $url = '', $isAudit = true, $pageParam = [], $forceDelete = false)
  {
    self::$btnList = [];
    foreach ($list as $name) {
      $item['component_url'] = str_replace('_', '-', $item['url']);
      if ($name == 'edit') {
        self::editBtn($item, $isAudit, $pageParam['edit_btn_param'] ?? [], $pageParam['edit_querys'] ?? []);
      } elseif ($name == 'recall') {
        self::recallBtn($item);
      } elseif ($name == 'read') {
        self::readBtn($item, $isAudit, $pageParam['read_btn_param'] ?? []);
      } elseif ($name == 'read-edit') {//read页面和edit页面， 共用一个页面
        self::readEditBtn($item, $isAudit, $pageParam['read_btn_param'] ?? []);
      }elseif ($name == 'print') {
        self::printBtn($item, $url);
      } else if ($name == 'delete') {
        self::deleteBtn($item, $isAudit, $forceDelete);
      }
    }
    return self::$btnList;
  }


  /**编辑按钮
   * @param         $item
   * @param boolean $isAudit true：审批数据 false 非审批数据
   * @param         $btn_arr 额外的btn参数
   * @return array|void
   */
  static function editBtn($item, $isAudit = true, $btn_arr = [],$querys=[])
  {
    $btn = [
      'type' => 'create',
      'title' => '修改',
      'url' => $item['url'],
      'component' => "{$item['component_url']}-create",
      'data_url' => "{$item['url']}/{$item['id']}/edit",
      'noAuth' => true,
      'save_btn_name' => $item['save_btn_name'] ?? '保存',
      'submit'=>$item['submit']??true,
      'save'=>$item['save']??true,
      'querys'=>$querys??[],
    ];
    if ($btn_arr) {
      $btn = array_merge($btn, $btn_arr);
    }
    //判断逻辑优化， 先判断是否退回、草稿，再进入处理。
    if ($isAudit) {
      if (in_array($item['status'], [1, 4, 6])) {
        if (empty($item['step_id']) || $item['step_id'] == 0) {
          if (is_ceo() || (!empty($item['creator']) && $item['creator'] == UID)) {
            self::$btnList[] = $btn;
          } else {
            $handlers = Db::name('apm_item')->alias('t1')
              ->leftJoin('apm_item_uid_access t2', 't2.item_id=t1.id AND t2.step_id=t1.next_step_id')
              ->where('t1.table_name', $item['url'] ?? get_table_name())
              ->where('t1.table_id', $item['table_id'] ?? $item['id'])
              ->value('GROUP_CONCAT(CONCAT_WS(",",t2.uid,t2.uid_entrust) SEPARATOR ",")');

            if (in_array(UID, explode(',', $handlers))) {
              self::$btnList[] = $btn;
            }

          }
        }
      }
    } else {
      self::$btnList[] = $btn;
    }
    return $btn;
  }

  /**回测按钮
   * @param $item
   * @return array|void
   */
  static function recallBtn($item)
  {
    $btn = [
      'type' => 'read',
      'title' => '撤回',
      'url' => $item['url'],
      'data_url' => "{$item['url']}/{$item['id']}", #cca/12?recall=1
      'querys' => [
        ['name'=>'recall','value'=>1]
      ],
      'component' => "{$item['component_url']}-read",
      'noAuth' => true,
    ];
    $normal_status = $item['status'] == 3;
//    $project_status = $item['status'] >= 4 && $item['status'] < 100 && $item['status'] <> 6;
    $project_status = $item['status'] > 4 && $item['status'] < 100 && $item['status'] <> 6;
    if($item['status'] == 4 && key_exists('step_id',$item) && $item['step_id'] > 0){
      $project_status = true;
    }
    $is_in_status = $normal_status || $project_status;

    $ceo_status = is_ceo() && $is_in_status;
    $creator_status = (UID == $item['creator']) && $is_in_status;
    if ($ceo_status || $creator_status) {
      self::$btnList[] = $btn;
      return $btn;
    }
  }

  /**详情按钮
   * @param         $item
   * @param boolean $isAudit true：审批数据 false 非审批数据
   * @return array|void
   */
  static function readBtn($item, $isAudit = true, $btn_arr = [])
  {

    $btn = [
      'type' => 'read',
      'title' => $item['read_title'] ?? "详情",
      'url' => $item['url'],
      'data_url' => "{$item['url']}/{$item['id']}",
      'component' => "{$item['component_url']}-read",
      'noAuth' => true,
    ];
    if ($btn_arr) {
      $btn = array_merge($btn, $btn_arr);
    }
    //
    if ($isAudit) {
      $btn['title'] = $item['read_title'] ?? read_btn_title($item);
    }
    if (isset($item['status']) && $item['status'] == 2) {
      $btn['save'] = false;
      $btn['submit'] = false;
    }
    if (!$isAudit || (isset($item['status']) && $item['status'] != 1)) {
      self::$btnList[] = $btn;
      return $btn;
    }
  }

  /**详情按钮 - 与编辑共用页面
   * @param         $item
   * @param boolean $isAudit true：审批数据 false 非审批数据
   * @return array|void
   */
  static function readEditBtn($item, $isAudit = true, $btn_arr = [])
  {

    $btn = [
      'type' => 'read',
      'title' => $item['read_title'] ?? "详情",
      'url' => $item['url'],
      'data_url' => "{$item['url']}/{$item['id']}",
      'component' => "{$item['component_url']}-create",
      'noAuth' => true,
    ];
    if ($btn_arr) {
      $btn = array_merge($btn, $btn_arr);
    }
    //
    if ($isAudit) {
      $btn['title'] = $item['read_title'] ?? read_btn_title($item);
    }
    if (isset($item['status']) && $item['status'] == 2) {
      $btn['save'] = false;
      $btn['submit'] = false;
    }
    if (!$isAudit || (isset($item['status']) && $item['status'] != 1)) {
      self::$btnList[] = $btn;
      return $btn;
    }
  }
  /**打印按钮
   * @param $item
   * @return array|void
   */
  static function printBtn($item, $url)
  {
    if ($item['status'] != 1) {
      $controller = $item['controller_name'] ?? request()->controllerName;
      $btn =
        ['type' => 'print', 'component' => "{$item['component_url']}-print",
          'data_url' => 'xtsb/' . $controller . '/preview/' . $url,
          'title' => '打印', 'isSubmit' => false, 'querys' => [
          ['name' => 'id', 'value' => $item['id']],
        ]];
      self::$btnList[] = $btn;
      return $btn;
    }
  }

  /**删除按钮
   * @param         $item
   * @param boolean $isAudit true：审批数据 false 非审批数据
   * @return array
   */
  static function deleteBtn($item, $isAudit = true, $forceDelete = false)
  {
    $btn = [
      'type' => 'delete',
      'title' => '删除',
      'msg' => '确认删除？',
      'url' => $item['url'],
      'noAuth' => true,
      'data_url' => "{$item['url']}/{$item['id']}",
    ];
    if ($isAudit) {
      //草稿或者驳回至发起人
      if ($item['status'] == 1 || ($item['status'] == 4 && empty($item['step_id'])) || ($item['status'] == 6 && empty($item['step_id']))) {
        if (is_ceo() || $item['creator'] == UID) {
          self::$btnList[] = $btn;
          return $btn;
        }
      } else {
        if (is_ceo() || $forceDelete) {
          $btn['title'] = '强制删除';
          $btn['msg'] = $item['delete_msg'] ?? "删除后，数据不可恢复，请谨慎操作，确认删除？";
          self::$btnList[] = $btn;
          return $btn;
        }
      }
    } else {
      if (is_ceo() || $item['creator'] == UID) {
        self::$btnList[] = $btn;
        return $btn;
      }
    }

    if (isset($item['status']) && in_array($item['status'], [1, 4])) {
      return $btn;
    }

    return [];//$btn
  }

  static function createBtn($item)
  {
    $item['component_url'] = str_replace('_', '-', $item['url']);
    $btn = [
      'type' => 'create',
      'title' => $item['title'] ?? '新增',
      'url' => $item['url'],
      'data_url' => "{$item['url']}/create",
      'component' => "{$item['component_url']}-create",
      'noAuth' => $item['noAuth'] ?? false,
      'save_btn_name' => '保存',
      'submit'=>$item['submit']??true,
      'save'=>$item['save']??true
    ];
    if (isset($item['querys'])) {
      $btn['querys'] = $item['querys'];
    }
    self::$btnList[] = $btn;
    return $btn;
  }

  static function showBtns($list, $is_clear = false)
  {
    if ($is_clear) {
      self::$btnList = [];
    }
    foreach ($list as $item) {
      if ($item['isShow']) {
        self::$btnList[] = self::customBtn($item);
      }
    }
  }

  /**自定义按钮
   * @param $item array 参数 url-必填  无其他参数 默认生成新增按钮
   * @return array
   */
  static function customBtn($item)
  {
    $url = $item['url'];
    $component_prefix = str_replace('_', '-', $url);
    $type = $item['type'] ?? 'create';

    if (isset($item['dynamic_type'])) {
      $controller = ucfirst(self::camelize($url));
      $data_url = "xtsb/{$controller}/{$item['dynamic_type']}/{$item['root']}";
      $component_suffix = $item['dynamic_type'];
    } elseif (isset($item['type']) && ($item['type'] == 'index' || $item['type'] == 'status')) {
      $data_url = $item['data_url'];
      $component_suffix = '';
    } else {
      $data_url = $item['data_url'] ?? "{$url}/{$type}";
      $component_suffix = str_replace('_', '-', $type);
    }


    $btn = [
      'url' => $url,   #cca
      'type' => $item['type'] ?? ($item['dynamic_type'] ?? 'create'),   #create
      'title' => $item['title'] ?? "新增",    #新增
      'data_url' => $data_url,      # cca/create
      'component' => $item['component'] ?? null, #cca-create
      'noAuth' => $item['noAuth'] ?? false,   #false
      'querys' => $item['querys'] ?? [],
//      'save_btn_name' => '保存',
      'save'=>$item['save']??true,
    ];
    if($btn['save']){
      $btn['save_btn_name'] = '保存';
    }
    if (isset($item['submit'])) {
      $btn['submit'] = $item['submit'];
    }
    if (in_array($btn['type'], ['create', 'edit', 'read', 'index']) || isset($item['dynamic_type'])) {
      $btn['component'] = $item['component'] ?? "{$component_prefix}-{$component_suffix}";
    }

    if (isset($item['msg'])) {
      $btn['msg'] = $item['msg'];
    }


    if (isset($item['save'])) {
      $btn['save'] = $item['save'];
    }

    //是否有辅助数据
    if (isset($item['querys'])) {
      $btn['querys'] = [];
      foreach ($item['querys'] as $name => $value) {
        if (is_numeric($name)) {
          $btn['querys'][] = $value;
        } else {
          $btn['querys'][] = ['name' => $name, 'value' => $value];
        }
      }
    }
    return $btn;
  }

  static function dropDownBtns($list, $title = '更多操作')
  {
    $drop_down = [
      'type' => 'dropdown', 'title' => $title, 'noAuth' => true, 'btnList' => []
    ];
    foreach ($list as $item) {
      $is_show = $item['isShow'] ?? true;
      if ($is_show) {
        $drop_down['btnList'][] = self::customBtn($item);
      }
    }
    self::$btnList[] = $drop_down;
    return $drop_down;
  }


  /**页面输出
   * @param Paginator $list 分页数据
   * @param array $btn 按钮
   * @param array $table 页眉数据
   * @param array $search 搜索
   * @return array
   */
  static function resultRender(Paginator $list, array $btn, array $table, array $search): array
  {
    return [
      'list' => $list->items(),
      'total_number' => $list->total(),
      'btn' => ButtonData::render($btn),
      'table' => $table,
      'search' => $search,
    ];
  }

  static function getSelect($data)
  {
    $list = [];
    foreach ($data as $each) {
      $list[] = ['value' => $each, 'label' => $each];
    }
    return $list;
  }

  static function getSelectByKv($data)
  {
    $list = [];
    foreach ($data as $value => $label) {
      $list[] = ['value' => $value, 'label' => $label];
    }
    return $list;
  }

  static function backBtn()
  {
    return ['type' => 'back', 'title' => '返回', 'noAuth' => true];
  }

  private static function camelize($uncamelized_words, $separator = '_')
  {
    $uncamelized_words = $separator . str_replace($separator, " ", strtolower($uncamelized_words));
    return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator);
  }
}
